<!-- 注册页面 -->
<script setup>
import { ref, computed, reactive } from "vue";
import { Icon } from "@iconify/vue";
import { useI18n } from "vue-i18n";
import { message } from "ant-design-vue";
import { UserOutlined, LockOutlined } from "@ant-design/icons-vue";
import { useLayoutThemeStore } from "@/store/layout/layoutTheme.js";
import { useUserStore } from "@/store/business/user.js";
import { useRouter } from "vue-router";

const { t } = useI18n();
const layoutSetting = useLayoutThemeStore().layoutSetting;
const borderRadius = computed(() => layoutSetting.borderRadius);
const userStore = useUserStore();

const formRef = ref();
const formState = ref({
  phone: "",
  password: "",
  confirmPassword: "",
  agree: false,
});

const iconLoading = ref(false);

// 手机号校验正则表达式
const phoneRegex = /^1[3-9]\d{9}$/;
const gerCaptcha = () => {
  if (!formState.value.phone) {
    message.error(t("message.pleaseEnterPhone"));
    return;
  }
  if (!phoneRegex.test(formState.value.phone)) {
    message.error(t("message.invalidPhoneNumber"));
    return;
  }
  startCountdown();
  console.log(1111, "111-验证码");
};
// 验证码
const countdownConfig = reactive({
  seconds: 60,
  isCountingDown: false,
  timerId: null,
});
const startCountdown = () => {
  if (!countdownConfig.isCountingDown) {
    countdownConfig.isCountingDown = true;
    countdownConfig.timerId = setInterval(() => {
      if (countdownConfig.seconds > 0) {
        countdownConfig.seconds--;
      } else {
        clearInterval(countdownConfig.timerId);
        countdownConfig.isCountingDown = false;
        countdownConfig.seconds = 60; // 重置秒数
      }
    }, 1000);
  }
};

const validatePass = async (_rule, value) => {
  if (value === "") {
    return Promise.reject(t("message.pleaseEnterPassword"));
  } else {
    if (formState.value.confirmPassword !== "") {
      formRef.value.validateFields(t("message.pleaseEnterTwoConfirmPassword"));
    }
    return Promise.resolve();
  }
};
const validatePass2 = async (_rule, value) => {
  if (value === "") {
    return Promise.reject(t("message.pleaseEnterReinputPassword"));
  } else if (value !== formState.value.password) {
    return Promise.reject(t("message.pleaseEnterInconsistencyPassword"));
  } else {
    return Promise.resolve();
  }
};

// 勾选校验
const checkAgreement = (rule, value) => {
  if (!value) {
    return Promise.reject(new Error(t("message.pleaseEnterAgree")));
  }
  return Promise.resolve();
};

const router = useRouter();
const onFinish = async (values) => {
  console.log("Success:", values), (iconLoading.value = true);

  // if (formState.value.loginType === 'phone') {
  //   // message.error(t('message.verifyCodeError'))
  //   formState.value.verifyCode = ''
  //   return
  // }

  userStore.login({
    username: formState.value.username,//账号
    password: formState.value.password,
    phone: formState.value.phone,
    captcha: formState.value.captcha,//验证码
    loginType: formState.value.loginType,
    agree: formState.value.agree,// 是否同意协议
  });
  // await router.push("/login");
  message.success(t("message.sigininSuccess"));

  // 测试动态路由（在这里动态增加路由）
};

const onFinishFailed = (errorInfo) => {
  console.log("Failed:", errorInfo);
};
</script>

<template>
  <a-form
    ref="formRef"
    :model="formState"
    @finish="onFinish"
    @finishFailed="onFinishFailed"
  >
    <a-form-item
      name="phone"
      :rules="[{ required: true, message: t('message.pleaseEnterPhone') }]"
    >
      <a-input
        v-model:value="formState.phone"
        :placeholder="t('message.pleaseEnterPhone')"
      >
      </a-input>
    </a-form-item>
    <a-form-item
      name="captcha"
      :rules="[{ required: true, message: t('message.pleaseEnterVerifyCode') }]"
    >
      <a-input
        v-model:value="formState.captcha"
        :placeholder="t('message.pleaseEnterVerifyCode')"
      >
        <template #suffix>
          <span @click="gerCaptcha" style="cursor: pointer; color: #31bc63">{{
            countdownConfig.seconds != 60 ? `${countdownConfig.seconds}秒` : "获取验证码"
          }}</span>
        </template>
      </a-input>
    </a-form-item>
    <!-- <a-form-item
      name="password"
      :rules="[{ required: true, message: t('message.pleaseEnterPassword') }]"
    >
      <a-input-password v-model:value="formState.password" :placeholder="t('message.pleaseEnterPassword')">
        <template #prefix>
          <LockOutlined />
        </template>
      </a-input-password>
    </a-form-item>
    <a-form-item
      name="confirmPassword"
      :rules="[{ required: true, message: t('message.pleaseEnterConfirmPassword') }]"
    >
      <a-input-password v-model:value="formState.confirmPassword" :placeholder="t('message.pleaseEnterConfirmPassword')">
        <template #prefix>
          <LockOutlined />
        </template>
      </a-input-password>
    </a-form-item> -->

    <a-form-item
      has-feedback
      name="password"
      :rules="[
        {
          required: true,
          validator: validatePass,
          trigger: 'change',
        },
      ]"
    >
      <a-input
        v-model:value="formState.password"
        type="password"
        autocomplete="off"
        :placeholder="t('message.pleaseEnterPassword')"
      />
    </a-form-item>
    <a-form-item
      has-feedback
      name="confirmPassword"
      :rules="[
        {
          validator: validatePass2,
          trigger: 'change',
        },
      ]"
    >
      <a-input
        v-model:value="formState.confirmPassword"
        type="password"
        autocomplete="off"
        :placeholder="t('message.pleaseEnterConfirmPassword')"
      />
    </a-form-item>

    <a-form-item name="agree" :rules="[{ validator: checkAgreement, trigger: 'change' }]">
      <a-checkbox v-model:checked="formState.agree">
        <span style="font-size: 12px">
          我已阅读并同意百分网《<a href="/developer-agreement" class="login-tip"
            >开发者协议条款</a
          >》和《<a href="/privacy-policy" class="login-tip">隐私政策</a>》
        </span>
      </a-checkbox>
    </a-form-item>
    <a-form-item>
      <a-button class="w100%" type="primary" :loading="iconLoading" html-type="submit">
        {{ t("setting.signIn") }}
      </a-button>
    </a-form-item>
  </a-form>
</template>

<style scoped lang="less">
.login-tip {
  font-size: 12px;
  text-align: center;
  color: #31bc63;
  cursor: pointer;
  font-style: normal;
}
.login_mode {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
